package com.younge.spring.component.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.younge.spring.api.common.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
@Slf4j
public class ResponseWrapper implements ResponseBodyAdvice<Object> {
    private final ObjectMapper mapper;

    public ResponseWrapper(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return !returnType.hasMethodAnnotation(IgnoreResponseWrap.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<?
                                          extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        try {
            // 如果已经是Result类型，直接返回
            if (body instanceof CommonResult) {
                if (log.isDebugEnabled()) {
                    log.debug("响应信息：{}", mapper.writeValueAsString(body));
                }
                return body;
            }

            // 如果是字符串，需要特殊处理，否则会报类型转换错误
            if (body instanceof String) {
                CommonResult<String> result = CommonResult.success((String) body);
                log.debug("响应信息：{}", mapper.writeValueAsString(result));
                return mapper.writer().writeValueAsString(result);
            }

            // 分页对象自动封装，还是放在原来的地方处理，避免warn
//            if (body instanceof PageImpl) {
//                return CommonResult.success(PageResult.of((PageImpl) body));
//            }
            CommonResult<Object> result = CommonResult.success(body);
            if (log.isDebugEnabled()) {
                log.debug("响应信息：{}", mapper.writeValueAsString(result));
            }
            return result;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

    }
}
